<template>
	<view class="square-container" :class="{ 'mobile': isMobile }">
		<!-- 背景装饰 -->
		<view class="background-overlay"></view>
		
		<!-- 头部 -->
		<view class="header">
			<view class="header-title-container">
				<i class="header-icon fas fa-bullhorn"></i>
				<view>
					<h1 class="header-title">动态广场</h1>
					<p class="header-subtitle">分享与发现生活中的每一个瞬间</p>
				</view>
			</view>
			<button class="post-btn" @tap="showPostModal">
				<i class="fas fa-plus"></i> 发布动态
			</button>
		</view>

		<!-- 筛选条 -->
		<view class="filter-bar">
			<button
				v-for="item in sortOptions"
				:key="item.value"
				:class="['filter-btn', currentSort === item.value ? 'active' : '']"
				@tap="changeSort(item.value)"
			>
				<i class="fas" :class="item.icon"></i>
				{{ item.label }}
			</button>
		</view>

		<!-- 动态列表 -->
		<scroll-view
			class="posts-list"
			scroll-y
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
			<view
				v-for="post in posts"
				:key="post.id"
				class="post-card fade-in-up"
			>
				<view class="post-header">
					<view class="post-author">
						<image :src="getAvatarUrl(post.userAvatar)" class="post-avatar" />
						<view class="author-info">
							<text class="author-name">{{ post.userName }}</text>
							<text class="post-time">{{ formatTime(post.created_at || post.CreatedAt) }}</text>
						</view>
					</view>
				</view>
				
				<view class="post-content">
					<text>{{ post.content }}</text>
				</view>
				
				<view class="post-actions">
					<button class="post-action" :class="{ 'liked': post.isLiked }" @tap="handleLike(post)">
						<i class="fa" :class="post.isLiked ? 'fas fa-heart' : 'far fa-heart'"></i>
						<text>{{ post.likes || 0 }}</text>
					</button>
					<button class="post-action" @tap="showComments(post)">
						<i class="far fa-comment"></i>
						<text>{{ post.comments_count || 0 }}</text>
					</button>
				</view>
			</view>
			
			<!-- 加载状态 -->
			<uni-load-more :status="loadingStatus"></uni-load-more>
		</scroll-view>
		
		<!-- 发布动态模态框 -->
		<view class="modal" v-if="showPostModalFlag">
			<view class="modal-content">
				<view class="modal-header">
					<h3>发布动态</h3>
					<button class="close-btn" @tap="closePostModal">×</button>
				</view>
				<textarea 
					class="post-textarea" 
					v-model="postContent" 
					placeholder="分享你的想法..."
					maxlength="500"
				></textarea>
				<view class="modal-footer">
					<button class="cancel-btn" @tap="closePostModal">取消</button>
					<button class="submit-btn" @tap="submitPost">发布</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getAllPosts, likePost, getPostComments, addComment, createPost } from '@/api/post';
import { addPointsForPost } from '@/api/points';
import { generateAvatarSvg } from '@/utils/avatar';
import { formatTime } from '../../utils/date-utils';
import { validateBeforeOperation, getCurrentUserId } from '@/utils/auth';
import uniLoadMore from '@dcloudio/uni-ui/lib/uni-load-more/uni-load-more.vue';

const PAGE_SIZE = 10;

export default {
	components: {
		uniLoadMore
	},
	data() {
		return {
			posts: [],
			currentPage: 1,
			hasMore: true,
			isLoading: false,
			isRefreshing: false,
			currentSort: 'latest',
			sortOptions: [
				{ label: '最新', value: 'latest', icon: 'fa-clock' },
				{ label: '热门', value: 'hot', icon: 'fa-fire' }
			],
			isMobile: false,
			showPostModalFlag: false,
			postContent: '',
			isSubmitting: false
		};
	},
	computed: {
		loadingStatus() {
			if (this.isLoading) {
				return 'loading';
			}
			if (!this.hasMore) {
				return 'noMore';
			}
			return 'more';
		}
	},
	onLoad() {
		// 检查用户是否已登录
		const isLoggedIn = validateBeforeOperation('访问动态广场');
		if (!isLoggedIn) {
			return;
		}
		const systemInfo = uni.getSystemInfoSync();
		this.isMobile = systemInfo.windowWidth < 768;
		this.isTablet = systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 1024;
		this.isDesktop = systemInfo.windowWidth >= 1024;
		this.loadPosts(true);
	},
	
	onShow() {
		// 每次显示页面时重新加载数据
		this.loadPosts(true);
	},
	methods: {
		getAvatarUrl(config) {
			return generateAvatarSvg(config);
		},
		async loadPosts(reset = false) {
		if (this.isLoading) return;
		this.isLoading = true;
		
		// 使用统一的用户ID获取方法
		const userId = getCurrentUserId(false) || 0;
		
		if (reset) {
			this.currentPage = 1;
			this.posts = [];
			this.hasMore = true;
		}

		try {
			const result = await getAllPosts({
				page: this.currentPage,
				orderBy: this.currentSort,
				userId: userId
			});

			if (result && Array.isArray(result) && result.length > 0) {
				const formattedPosts = result.map(post => ({
					...post,
					isLiked: post.is_liked || false,
					isLiking: false,
					userName: post.user ? post.user.name : '匿名用户',
					userAvatar: post.user ? post.user.avatar : null,
				}));
				this.posts = [...this.posts, ...formattedPosts];
				this.currentPage++;
				this.hasMore = result.length === PAGE_SIZE;
			} else {
				this.hasMore = false;
			}
		} catch (error) {
			console.error('加载动态失败:', error);
			uni.showToast({ title: '加载失败', icon: 'none' });
		} finally {
			this.isLoading = false;
			if (this.isRefreshing) {
				this.isRefreshing = false;
			}
		}
		},
		
		async onRefresh() {
			this.isRefreshing = true;
			try {
				await this.loadPosts(true);
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				});
			} catch (error) {
				console.error('下拉刷新失败:', error);
				uni.showToast({
					title: '刷新失败，请稍后再试',
					icon: 'error'
				});
			} finally {
				this.isRefreshing = false;
			}
		},
		
		loadMore() {
			if (this.hasMore && !this.isLoading) {
				this.loadPosts();
			}
		},
		
		changeSort(sort) {
			if (this.currentSort === sort) return;
			this.currentSort = sort;
			this.loadPosts(true);
		},
		
		async handleLike(post) {
		if (post.isLiking) return; // 防止重复点击
		post.isLiking = true;
		try {
			const result = await likePost(post.id);
			// 根据后端返回结果更新状态
			post.isLiked = result.isLiked;
			post.likes = result.likes;
		} catch (error) {
			console.error('点赞失败:', error);
			uni.showToast({ title: '操作失败', icon: 'none' });
		} finally {
			post.isLiking = false;
		}
		},
		
		showComments(post) {
			uni.showToast({ title: '评论功能正在赶来的路上...', icon: 'none' });
		},
		
		formatTime,
		
		// 显示发布动态模态框
		showPostModal() {
			this.showPostModalFlag = true;
		},
		
		// 关闭发布动态模态框
		closePostModal() {
			this.showPostModalFlag = false;
			this.postContent = '';
		},
		
		// 提交动态
		async submitPost() {
			if (!this.postContent.trim()) {
				uni.showToast({ title: '内容不能为空', icon: 'none' });
				return;
			}
			
			// 使用统一的登录验证
			const isLoggedIn = validateBeforeOperation('发布动态')
			
			if (!isLoggedIn) {
				return;
			}
			
			this.isSubmitting = true;
			try {
				await createPost({
					content: this.postContent
				});
				
				// 添加积分奖励
				try {
					await addPointsForPost();
					console.log('积分奖励添加成功');
				} catch (pointsError) {
					console.error('积分奖励添加失败:', pointsError);
				}
				
				this.closePostModal();
				uni.showToast({ title: '发布成功！', icon: 'success' });
				await this.loadPosts(true);
			} catch (error) {
				console.error("发布动态失败:", error);
				uni.showToast({ title: '发布失败', icon: 'error' });
			} finally {
				this.isSubmitting = false;
			}
		}
	}
};
</script>

<style scoped src="./square.css"></style>
<style scoped>
.post-action.liked {
	color: #ff4d4f;
}

.post-action:disabled {
	opacity: 0.7;
}

.post-action loading {
	margin-left: 5rpx;
}
</style>